const http = require(`http`)
const fs = require("fs")

const server = http.createServer((req, res) => {
    let uri = req.url
 
    if (uri === `/`) {
        uri = `/index.html`
    } else if (uri.includes(`?`)) {
        uri = uri.split(`?`)[0]
    } else if (uri === `/register`) {
        getPostData(req, function (obj) {
            let data = fs.readFileSync(`./user.json`, `utf8`)
            if (data) {
                data = JSON.parse(data)
            } else {
                data = []
            }
            data.push(obj)
            fs.writeFileSync(`./user.json`, JSON.stringify(data))

            responseFn(res, {
                code: 1,
                msg: `注册成功`
            })
            console.log(obj)
            // res.setHeader(`content-type`, `text/html;charset=utf8`)
            // res.end(JSON.stringify(pbj))

        })
        return
    } else if (uri === `/login`) {
        getPostData(req, function (obj) {

            let data = fs.readFileSync(`./user.json`, `utf8`)
            data = JSON.parse(data)
            console.log(data)
            let user = data.find(item => item.username === obj.username && item.password === obj.password)
            if (data) {
                if (user) {
                    responseFn(res, {
                        code: 1,
                        msg: `登陆成功`
                    })
                } else {
                    responseFn(res, {
                        code: 2,
                        msg: `用户名或密码错误`
                    })
                }
            } else {
                responseFn(res, {
                    code: 0,
                    msg: `请先注册`
                })
            }

        })

        return



    } else if (uri === `/getGoods`) {
        let data = fs.readFileSync(`./goods.json`, `utf-8`)

        data = JSON.parse(data)
        res.end(JSON.stringify({
            code: 1,
            msg: `获取数据成功`,
            data: data
        }))

        return
    } else if (uri === `/getGoodlist`) {
        let data = fs.readFileSync(`./goodlist.json`, `utf-8`)

        data = JSON.parse(data)
        res.end(JSON.stringify({
            code: 1,
            msg: `获取数据成功`,
            data: data
        }))

        return
    } else if (uri === '/getUser') {
        let str = ''
        
        req.on('data', chunk => {
            str += chunk.toString()
        })
        req.on('end', () => {
            // 将数组转成对象
            let obj = {}
            let arr = str.split('&')
            arr.forEach(item => {
                let brr = item.split('=')
                obj[brr[0]] = brr[1]
            })
            // 读取所有用户信息
            let data = fs.readFileSync('./user.json', 'utf-8')
            data = JSON.parse(data)
            // 从data中筛选出当前用户的数据
            let userData = data.find(item => item.username === obj.username)
            // 从用户数据中删除密码
            delete userData.password
            res.end(JSON.stringify({
                code: 1,
                msg: '获取用户数据成功',
                data: userData
            }))
            return
        })
        return
    } else if (uri === '/updateUser') {
        let str = ''
        req.on('data', chunk => {
            str += chunk.toString()
        })
        req.on('end', () => {
            // 将数组转成对象
            let obj = {}
            let arr = str.split('&')
            arr.forEach(item => {
                let brr = item.split('=')
                obj[brr[0]] = brr[1]
            })

            var cookiesArr = req.headers.cookie.split('&');
            for (var a = 0; a < cookiesArr.length; a++) {
                var brr = cookiesArr[a].split('=')
                if (brr[0] === 'username') {
                    var username = brr[1]
                }
            }
            var data = fs.readFileSync('./user.json', 'utf-8')
            data = JSON.parse(data)
            var userData = data.find(item => item.username === username)
            var condition = data.find(item => item.username === obj.username)
            if (condition) {
                res.end(JSON.stringify({
                    code: 0,
                    msg: '用户名被占用了'
                }))
                return
            }
            for (var i in obj) {
                userData[i] = obj[i]
            }
            fs.writeFileSync('./user.json', JSON.stringify(data))
            res.end(JSON.stringify({
                code: 1,
                msg: '用户信息修改成功'
            }))
        })

        return
    }






    let data = fs.readFileSync(`./public` + uri)
    res.end(data)

})
server.listen(9966, () => {
    console.log('server is running at http://localhost:9966');
})

function getPostData(req, fn) {
    let str = ""
    req.on(`data`, chunk => {
        str += chunk.toString()
    })
    req.on(`end`, () => {
        let arr = str.split(`&`)
        let obj = {}
        arr.forEach(item => {
            let brr = item.split(`=`)
            obj[brr[0]] = brr[1]
        })
        fn(obj)
    })

}


function responseFn(res, pbj) {
    res.setHeader(`content-type`, `text/htm l;charset=utf8`)
    res.end(JSON.stringify(pbj))
}